package com.lvyp.server.config.filter;

import com.lvyp.server.pojo.Menu;
import com.lvyp.server.pojo.Role;
import com.lvyp.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * security自定义权限拦截
 * 根据请求URL分析请求所需的角色
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IMenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // 获取请求URL
        String requestUrl = ((FilterInvocation)object).getRequestUrl();
        // 根据角色查询菜单列表
        List<Menu> menus = menuService.getMenusWithRole();
        // 遍历菜单列表
        for (Menu menu : menus) {
            // 判断 从请求获取的URL和数据库查询的URL 进行比较
            if (antPathMatcher.match(menu.getUrl(),requestUrl)) {
                // 将匹配上的角色放到数组
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(str);
            }
        }
        // 没匹配的URL默认登录即可访问，默认角色
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
